import React from 'react';
import {View, Text, Button} from 'react-native';
import {Todo} from '../todoSlice';

type Props = {
  todo: Todo;
  onDelete: () => void;
  onToggleState: () => void;
};
function formatToEnglishDate(isoString: string): string {
  const date = new Date(isoString);

  const monthNames = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];

  const month = monthNames[date.getMonth()];
  const day = date.getDate();
  const year = date.getFullYear();

  const hours = date.getHours();
  const ampm = hours >= 12 ? 'PM' : 'AM';

  return `${month} ${day} ${year} ${ampm}`;
}

interface StateButtonProps {
  state: 'todo' | 'pending' | 'done';
  onPress: () => void;
}
const StateButton: React.FC<StateButtonProps> = ({state, onPress}) => {
  let title = '';
  let color = '';
  if (state === 'todo') {
    title = 'Start';
    color = 'orange';
  } else if (state === 'pending') {
    title = 'Done';
    color = 'green';
  } else {
    title = '';
    color = 'gray';
  }
  if (state === 'todo' || state === 'pending') {
    return <Button title={title} color={color} onPress={onPress} />;
  } else {
    return null;
  }
};
const TodoItem: React.FC<Props> = ({todo, onDelete, onToggleState}) => {
  return (
    <View className="p-2 bg-white">
      <View className="flex-row justify-between items-center px-[10%]">
        <View className="flex-1">
          <Text className=" text-xl font-semibold mt-2">{todo.task}</Text>
          <Text className="text-sm text-gray-500 mt-2">
            {formatToEnglishDate(todo.startTime)}
          </Text>
          <Text className="text-sm text-gray-500 mt-2">
            {formatToEnglishDate(todo.endTime)}
          </Text>
        </View>
        <View>
          <StateButton state={todo.state} onPress={onToggleState} />
          <Button title="Delete" color="red" onPress={onDelete} />
        </View>
      </View>
    </View>
  );
};

export default TodoItem;
